package com.kordar.admin.modular.sys.controller;

import com.kordar.admin.enums.CommonActive;
import com.kordar.admin.modular.sys.entity.LoginForm;
import com.kordar.admin.modular.sys.entity.TenantEntity;
import com.kordar.admin.modular.sys.service.TenantService;
import com.kordar.datalist.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Controller
public class AuthController {

    final
    TenantService tenantService;

    public AuthController(TenantService tenantService) {
        this.tenantService = tenantService;
    }

    @PostMapping("/login")
    @ResponseBody
    public ResultEntity<Object> login(LoginForm form, HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(form.getUsername(), form.getPassword());
        try {

            // 如果设置了租户
            if (StringUtils.hasText(form.getTenantCode())) {
                TenantEntity te = tenantService.findOneByCode(form.getTenantCode());
                if (te != null && !te.getActive().equals(CommonActive.OPEN.getCode())) {
                    return ResultEntity.error("租户已停用，禁止登入！");
                }
                subject.getSession().setAttribute("tenant", form.getTenantCode());
                subject.getSession().setAttribute("datasource", te.getDatasource());
            }


            // request.setAttribute("login-tenant", form.getTenantCode());
            subject.login(token);

        } catch (AuthenticationException e) {
            log.error("用户[" + form.getUsername() + "] 登录失败（" + e.getMessage() + "）");
            return ResultEntity.error(e.getMessage());
        }
        log.info("用户[" + form.getUsername() + "] 登录成功");
        return ResultEntity.success();
    }

    @RequestMapping(value = "/logout", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ResultEntity<Object> logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResultEntity.success();
    }
}
